<template>
  <div>
    <div style="align-content: center;">
      <el-form :rules="rules" ref="form" :model="form" label-width="80px">
        <el-form-item label="视频">
          <el-upload
            class="upload-demo"
            drag
            action
            :file-list="fileList"
            :http-request="uploadOnServer"
            :before-upload="beforeVideoUpload"
            :on-change="onProgressVideo"
            :limit="1"
            :on-exceed="onExceed"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或
              <em>点击上传</em>
            </div>
            <div
              class="el-upload__tip"
              style="color:rgb(154, 198, 255);font-size:10px;padding-left:10px"
              slot="tip"
            >
              封面支持png,jpg,jpeg,pdf,bmp格式文件，尺寸：，且大小不超过20MB
              <br />视频支持avi,mpg,mpeg,mp4格式文件，且不超过500MB
            </div>
          </el-upload>

          <div v-if="elProgressVideo">
            <el-progress
              :percentage="progressPercentVideo"
              :text-inside="true"
              :stroke-width="16"
              status="success"
            ></el-progress>
          </div>

          <div v-if="elProgressCover">
            <el-progress
              :percentage="progressPercentCover"
              :text-inside="true"
              :stroke-width="16"
              status="success"
            ></el-progress>
          </div>
        </el-form-item>
        <el-form-item label="封面">
          <div>
            <!-- auto-upload 默认为true，此时不会调用action和自己写的http-request的接口 -->

            <el-upload
              action
              list-type="picture-card"
              :auto-upload="false"
              :limit="1"
              :on-change="change"
              :on-exceed="onExceed"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog title="封面预览" width="80%" :visible.sync="dialogFormVisible" center>
              <img :src="coverUrl" alt />
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmCoverImg">确 定</el-button>
              </div>
            </el-dialog>
          </div>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="分区" prop="part">
          <el-select v-model="form.part" multiple :multiple-limit="5" placeholder="请选择分区">
            <el-option
              v-for="item in partList"
              :key="item.partionId"
              :label="item.partionName"
              :value="item.partionId"
            ></el-option>
          </el-select>
          <span style="color:rgb(154, 198, 255);font-size:10px;padding-left:10px">*最多选择5个分区</span>
        </el-form-item>

        <el-form-item label="类型" prop="resource">
          <el-radio-group v-model="form.resource">
            <el-radio label="Y">自制</el-radio>
            <el-radio label="N">转载</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="简介">
          <el-input
            type="textarea"
            :autosize="{ minRows: 5}"
            maxlength="1000"
            show-word-limit
            v-model="form.desc"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('form')">立即投稿</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: "uploadvideo",

  data() {
    return {
      videoType: "",
      progressPercentVideo: 0,
      progressPercentCover: 0,
      elProgressVideo: false,
      elProgressCover: false,
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      coverUrl: "",
      form: {
        title: "",
        region: "",
        resource: "",
        part: "",

        desc: ""
      },
      dialogFormVisible: false,
      uploadId: "", //类upload的id，存的是视频的
      videoPath: "",
      coverFileId: "", //类upload的id，存的是图片的
      coverFilePath: "",
      partList: [
        {
          partionId: "1712489300190429184",
          partionName: "游戏",
          partionType: "video",
          createId: "1711410731683020800",
          createCode: "56292976232",
          createName: "bprogram",
          createTime: "2023-10-12T23:24:00",
          updateId: null,
          updateCode: null,
          updateName: null,
          updateTime: "2023-10-12T23:24:00"
        },
        {
          partionId: "1712489342825529344",
          partionName: "动漫",
          partionType: "video",
          createId: "1711410731683020800",
          createCode: "56292976232",
          createName: "bprogram",
          createTime: "2023-10-12T23:24:10",
          updateId: null,
          updateCode: null,
          updateName: null,
          updateTime: "2023-10-12T23:24:10"
        },
        {
          partionId: "1712489388258230272",
          partionName: "搞笑",
          partionType: "video",
          createId: "1711410731683020800",
          createCode: "56292976232",
          createName: "bprogram",
          createTime: "2023-10-12T23:24:21",
          updateId: null,
          updateCode: null,
          updateName: null,
          updateTime: "2023-10-12T23:24:21"
        },
        {
          partionId: "1712489819252326400",
          partionName: "科普",
          partionType: "video",
          createId: "1711410731683020800",
          createCode: "56292976232",
          createName: "bprogram",
          createTime: "2023-10-12T23:26:04",
          updateId: "1711410731683020800",
          updateCode: "56292976232",
          updateName: "bprogram",
          updateTime: "2023-10-12T23:26:55"
        },
        {
          partionId: "1712492900841029632",
          partionName: "国创",
          partionType: "video",
          createId: "1711410731683020800",
          createCode: "56292976232",
          createName: "bprogram",
          createTime: "2023-10-12T23:38:18",
          updateId: null,
          updateCode: null,
          updateName: null,
          updateTime: "2023-10-12T23:38:18"
        },
        {
          partionId: "1712493066209853440",
          partionName: "美食",
          partionType: "video",
          createId: "1711410731683020800",
          createCode: "56292976232",
          createName: "bprogram",
          createTime: "2023-10-12T23:38:58",
          updateId: null,
          updateCode: null,
          updateName: null,
          updateTime: "2023-10-12T23:38:58"
        },
        {
          partionId: "1712493095427375104",
          partionName: "运动",
          partionType: "video",
          createId: "1711410731683020800",
          createCode: "56292976232",
          createName: "bprogram",
          createTime: "2023-10-12T23:39:05",
          updateId: null,
          updateCode: null,
          updateName: null,
          updateTime: "2023-10-12T23:39:05"
        },

        {
          partionId: "1736764763058339840",
          partionName: "经典记录片",
          partionType: "video",
          createId: "1711410731683020800",
          createCode: "56292976232",
          createName: "bprogram",
          createTime: "2023-12-18T23:06:02",
          updateId: null,
          updateCode: null,
          updateName: null,
          updateTime: "2023-12-18T23:06:02"
        }
      ],
      coverFile: { file: "" },
      fileCategory: "", //类别：img照片，video：视频
      fileList: [],
      rules: {
        title: [
          {
            required: true,
            message: "请给你的视频取个标题吧",
            trigger: "blur"
          },
          {
            min: 1,
            max: 100,
            message: "标题长度超出限制",
            trigger: ["blur", "change"]
          }
        ],
        part: [
          {
            required: true,
            message: "请给你的视频选择分区",
            trigger: ["blur", "change"]
          }
        ],
        resource: [
          {
            required: true,
            message: "请选择你的视频类型",
            trigger: ["blur", "change"]
          }
        ]
      }
    };
  },
  created() {
    //获取视频分区列表
    this.getPartList();
  },

  methods: {
    confirmCoverImg() {
      this.dialogFormVisible = false;
      this.progressPercentCover = 0;
      this.elProgressCover = true;
      this.times = setInterval(() => {
        if (this.progressPercentCover > 97) {
          clearInterval(this.times);
          this.times = null;
        }
        //就算执行了if里面的方法销毁了计数器，还是会执行if后面的代码
        this.progressPercentCover++;
      }, 900);
      this.uploadOnServer(this.coverFile);
    },

    change(file, fileList) {
      let isAllowToUpload = this.beforeImgUpload(file.raw);
      if (isAllowToUpload) {
        this.coverUrl = file.url;
        // 将要上传的文件赋值过来
        this.coverFile.file = file.raw;
        this.dialogFormVisible = true;
      }
    },

    onExceed(files, fileList) {
      this.$message.warning("暂只可上传一个文件！");
    },

    //上传文件到服务器
    uploadOnServer(param) {
      var file = param.file;
      let params = new FormData();
      params.append("type", this.fileCategory);
      params.append("file", file);
      this.axios({
        method: "post",
        url: "http://localhost:8093/upload/uploadOnServer",
        data: params,
        headers: {
          "content-type": "multipart/form-data"
        },
        timeout: 600000
      })
        .then(res => {
          // res.data 后端返回的数据：
          this.handleAvatarSuccess(res, file);
          if (this.fileCategory === "img") {
            this.progressPercentCover = 100;
          }
          if (this.fileCategory === "video") {
            this.progressPercentVideo = 100;
          }
          this.$message.success("上传服务器成功");
        })
        .catch(err => {
          this.$message.error("上传服务器失败");
        });
    },

    getPartList() {
      this.axios({
        method: "post",
        params: {
          currentPage: "1",
          pageSize: 10000,
          type: "video"
        },
        url: "http://localhost:8092/partion/getPartionList"
      })
        .then(r => {
          this.partList = r.data;
        })
        .catch(e => {
           this.$message.error(e.response.data.message);
        });
    },
    onProgressVideo(event) {
      console.log(event);
      this.progressPercentVideo = 0;
      this.elProgressVideo = true;
      this.times = setInterval(() => {
        if (this.progressPercentVideo > 97) {
          clearInterval(this.times);
          this.times = null;
        }
        //就算执行了if里面的方法销毁了计数器，还是会执行if后面的代码
        this.progressPercentVideo++;
      }, 900);
    },

    handleAvatarSuccess(res, file) {
      //将文件信息保存到数据库
      const sourceName = res.data.substring(res.data.lastIndexOf("/") + 1);
      this.axios({
        method: "post",
        params: {
          fileType: file.type,
          fileSize: file.size,
          fileAssociation: this.fileCategory,
          fileName: file.name,
          filePath: res.data,
          fileSourceName: sourceName
        },
        url: "http://localhost:8093/upload/fileSaveOrUpdate"
      })
        .then(r => {
          if (this.fileCategory === "img") {
            this.coverFileId = r.data.fileId;
            this.coverFilePath = r.data.filePath;
            this.elProgressCover = false;
          } else if (this.fileCategory === "video") {
            this.uploadId = r.data.fileId;
            this.videoPath = r.data.filePath;
            this.videoType = file.type;
            this.elProgressVideo = false;
          }
          this.$message.success("保存数据库成功");
        })
        .catch(e => {
          this.$message.error("保存数据库失败");
        });
    },
    beforeImgUpload(file) {
      // png,jpg,jpeg,pdf,bmp

      const isPng = file.type === "image/png";
      const isJpg = file.type === "image/jpg";
      const isJpeg = file.type === "image/jpeg";
      const isPdf = file.type === "image/pdf";
      const isBmp = file.type === "image/bmp";
      const isLt20M = file.size / 1000 / 1000 < 20;

      let IsAllowUpload = false;
      if (isPng || isJpg || isJpeg || isPdf || isBmp) {
        if (isLt20M) {
          IsAllowUpload = true;
          this.fileCategory = "img";
        } else {
          this.$message.error("文件大小不能超过 20MB!");
        }
      } else {
        this.$message.error("图片格式错误，请重新上传！");
      }
      return IsAllowUpload;
    },
    beforeVideoUpload(file) {
      //  avi,mpg,mpeg,mp4
      const isMp4 = file.type === "video/mp4";
      const isAvi = file.type === "video/avi";
      const isMpg = file.type === "video/mpg";
      const isMpeg = file.type === "video/mpeg";
      const isLt500M = file.size / 1000 / 1000 < 500;
      let IsAllowUpload = false;
      if (isMp4 || isAvi || isMpg || isMpeg) {
        if (isLt500M) {
          this.fileCategory = "video";
          IsAllowUpload = true;
        } else {
          this.$message.error("文件大小不能超过 500MB!");
        }
      } else {
        this.$message.error("视频格式错误，请重新上传！");
      }
      return IsAllowUpload;
    },
    onSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.form.resource);
          if (this.uploadId === "" || this.videoPath === "") {
            this.$message.warning("请先上传视频后才可以进行发布！");
          } else if (this.coverFileId === "" || this.coverFilePath === "") {
            this.$message.warning("请选择视频封面后才进行视频发布！");
          } else {
            this.axios({
              method: "post",
              url: "http://localhost:8094/video/saveOrUpdateVideo",
              data: {
                uploadId: this.uploadId,
                videoPath: this.videoPath,
                videoTitle: this.form.title,
                videoIntroduct: this.form.desc,
                isOriginal: this.form.resource,
                videoType: this.videoType,
                videoLike: 0,
                videoCollects: 0,
                videoComments: 0,
                videoForward: 0,
                videoPlayTimes: 0,
                videoPartitionIds: this.form.part + "",
                isAllow: "Y",
                videoCoverId: this.coverFileId,
                videoCover: this.coverFilePath
              }
            })
              .then(res => {
                this.$message.success("发布成功");
                this.$router.push("/videoplay/"+res.data.videoId);
              })
              .catch(err => {
                this.$message.success("发布失败，请重新上传后，再次进行发布");
              });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style   scoped>
.avatar-uploader-icon {
  border: dashed 1px #d3d3d3;
  font-size: 28px;
  color: #8c939d;

  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader {
  width: 178px;
  height: 178px;
}
.avatar-uploader:hover {
  width: 178px;
  height: 178px;
  border: dashed 1px rgb(0, 179, 250);
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
